package com.gemme.gemme.login;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.gemme.gemme.BaseActivity;
import com.gemme.gemme.MainActivity;
import com.gemme.gemme.R;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.util.DpUtil;
import com.gemme.gemme.util.EMClientUtil;
import com.gemme.gemme.util.MobileUtil;
import com.gemme.gemme.util.SPUtil;
import com.gemme.gemme.util.ShapeUtil;
import com.gemme.gemme.view.MyButton;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.ChatClient;
import com.hyphenate.chat.EMClient;
import com.jaeger.library.StatusBarUtil;

import org.json.JSONObject;

import java.util.HashMap;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
/*
* 手机号登录
* 1,获取验证码
* 2,登录
* */
public class TelLoginActivity extends BaseActivity implements View.OnClickListener {
   Context context =  TelLoginActivity.this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_tel);
        StatusBarUtil.setTransparent(this);
        initView();
//        judge();
        requestPemission();
//        initTimer();
    }


    MyButton bt_confirm;
    EditText et_acount;
    EditText et_msg;
    TextView tv_code;
    private void initView() {
        bt_confirm = findViewById(R.id.bt_confirm);
        bt_confirm.setSatate(true);
        et_acount = findViewById(R.id.et_acount);
        et_msg = findViewById(R.id.et_msg);

        tv_code = findViewById(R.id.tv_code);

        tv_code.setOnClickListener(this);
        bt_confirm.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_code:
            //获取验证码
                String account = et_acount.getText() + "";
                if(TextUtils.isEmpty(account)){
                    Toast.makeText(context, "手机号不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                toMsg();

                break;

            case R.id.bt_confirm:
                //获取验证码
                toLogin();
                break;
        }
    }


    private void toLogin() {
        String account = et_acount.getText() + "";
        String url = DataManager.BaseUrl + "auth/mobile/token/sms?";
        if(TextUtils.isEmpty(account) || TextUtils.isEmpty(et_msg.getText().toString()) ){
            Toast.makeText(context, "手机号和验证码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

//        EMClientUtil.registeredAndLogin(mContext,account + "1472583690","1472583690");

        url = url + "phone=APPSMS@" + account
                +"&code=" + et_msg.getText().toString()+
                "&grant_type="+ "mobile" +
                "&invite_code="+ ""
        ;

        HashMap<String, String> hashmap = new HashMap<>();
        hashmap.put(DataManager.AuthorizationKey,DataManager.Authorization);
        DataManager.postDataToServerByHeader(context,url,"",hashmap,new DataManager.GeResponse() {
            @Override
            public void onResponse(String str) {
                try {
                    //登录成功后,添加环信登录
                    EMClientUtil.login(mContext,account,et_msg.getText().toString());
//                    EMClientUtil.registeredAndLoginBykefu(mContext,account,"123456");
                    EMClientUtil.loginBykefu(mContext,account,et_msg.getText().toString());
                    SharedPreferences MSP = context.getSharedPreferences(Constant.MSP, Context.MODE_PRIVATE);
                    UseInfoBean useInfos = JSON.parseObject(str,UseInfoBean.class);
                    if(!TextUtils.isEmpty(useInfos.getAccess_token()))
                        MSP.edit().putString(Constant.ACCESS_TOKEN, useInfos.getAccess_token()).apply();
                    if(!TextUtils.isEmpty(useInfos.getRefresh_token()))
                        MSP.edit().putString(Constant.REFRESH_TOKEN, useInfos.getRefresh_token()).apply();
                    if(!TextUtils.isEmpty(useInfos.getUser_info().getId()))
                        MSP.edit().putString(Constant.UserId, useInfos.getUser_info().getId() + "").apply();
                    MSP.edit().putString(Constant.ACCESS_TOKENTIME, System.currentTimeMillis() + "").apply();
                    MSP.edit().putString(Constant.REFRESH_TIME, System.currentTimeMillis() + "").apply();

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            DataManager.refreshToken(context);

                            Handler mainHandler = new Handler(Looper.getMainLooper());
                            mainHandler.post(() -> {
                                //登陆成功,首次进入个人信息页
                                ChatClient.getInstance().isLoggedInBefore();
                                Log.e("#######","SFLogin"+ ChatClient.getInstance().isLoggedInBefore());
                                String dataForString = SPUtil.getDataForString(context, Constant.isFirstLogin, "0");
                                if("0".equals(dataForString)){
                                    startActivity(new Intent(context,PersonInfoActivity.class));
                                    //去除是首次登录
                                    SPUtil.PutData(context, Constant.isFirstLogin, "-1");
                                }else{
                                    startActivity(new Intent(context,MainActivity.class));

                                }
//                    startActivity(new Intent(context, MainActivity.class));
                                finish();
                            });

                        }
                    }).start();



                }catch (Exception e){

                }
            }
        });

    }

    String msg ;
    private void toMsg() {
        String account = et_acount.getText() + "";

        if(TextUtils.isEmpty(account)){
            Toast.makeText(context, "手机号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if(!MobileUtil.checkPhone(account)){
            Toast.makeText(context, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }

        tv_code.setEnabled(false);
                /*tv_code.setBackground(ShapeUtil.setCornBgStrok(DpUtil.dp2px((Activity) context,4),"#ffffffff",
                        DpUtil.dp2px((Activity) context,1),"#FF9D2C2F"));*/
        initTimer();

//        String url = "http://192.168.1.6:9999/user/userapp/appmobile/15256987478";
        String url = DataManager.BaseUrl + "user/userapp/appmobile/" + account;
        DataManager.getDataFromServer(this, url, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                System.out.println("");
                try {
                    MsgBean msgBean = JSON.parseObject(response, MsgBean.class);

//                    msg = msgBean.getMsg();
//                    et_msg.setText(msg);
                }catch (Exception e){

                }

            }
        });
    }

    private void requestPemission() {
        if(Build.VERSION.SDK_INT>=23){
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.CALL_PHONE,Manifest.permission.READ_LOGS,Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.SET_DEBUG_APP,Manifest.permission.SYSTEM_ALERT_WINDOW,Manifest.permission.GET_ACCOUNTS,Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(this,mPermissionList,123);
        }
    }



    private void judge() {
        SharedPreferences MSP = getSharedPreferences(Constant.MSP, Context.MODE_PRIVATE);
         String access_token = MSP.getString(Constant.ACCESS_TOKEN, "").trim();

        if(!TextUtils.isEmpty(access_token)){
            startActivity(new Intent(context, MainActivity.class));
            finish();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }


    private void initTimer() {
        /**
         * CountDownTimer timer = new CountDownTimer(3000, 1000)中，
         * 第一个参数表示总时间，第二个参数表示间隔时间。
         * 意思就是每隔一秒会回调一次方法onTick，然后1秒之后会回调onFinish方法。
         */
        CountDownTimer timer = new CountDownTimer(60000, 1000) {
            public void onTick(long millisUntilFinished) {
                Log.d("TelLoginActivity","倒计时" + millisUntilFinished / 1000 + "秒");
                tv_code.setText(millisUntilFinished / 1000 + "秒后重新获取");
                if(millisUntilFinished / 1000 == 0){
                    tv_code.setEnabled(true);
                    tv_code.setBackgroundResource(0);
                    tv_code.setText("获取验证码");
                }

            }

            public void onFinish() {

            }
        };
        //调用 CountDownTimer 对象的 start() 方法开始倒计时，也不涉及到线程处理
        timer.start();
    }


}